package com.xy.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //1.创建selector
        Selector selector = Selector.open();
        //2.创建服务器监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //3.设置非阻塞
        serverSocketChannel.configureBlocking(false);
        //4.注册事件到selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //5.等待客户端连接
        while (true) {
            //阻塞1秒
            if (selector.select(1000) == 0) {
                //System.out.println("服务器等待了一秒,无连接");
                continue;
            }
            //获取相关SelectionKey集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍历处理连接
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                //根据key对应的通道发生的事件做相应处理
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功:" + socketChannel.hashCode());
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    //通过key反向获取channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("from 客户端:" + new String(buffer.array()));
                }
                keyIterator.remove();
            }
        }
    }
}
